package com.mdz.nc.Controller;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mdz.nc.Entity.SysUser;
import com.mdz.nc.Mapper.SysUserMapper;
import com.mdz.nc.Service.SysUserService;
import com.mdz.nc.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author 孟德志
 * @since 2020-03-28
 */
@Controller
@RequestMapping("/nc/sysUser")
public class SysUserController {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private HttpSession session;

    @ResponseBody
    @GetMapping(value = "/login/{loginName}/{loginPassword}")
    public List<SysUser> login(@PathVariable("loginName") String loginName, @PathVariable("loginPassword") String loginPassword, ModelMap map, HttpServletRequest request) {
        String Password = SecureUtil.md5(loginPassword);
        List<SysUser> user = sysUserMapper.selectList(new QueryWrapper<SysUser>().eq("login_name", loginName).eq("login_password", Password));
//        map.put("userName", user.get(0).getLoginName());
            session.setAttribute("username", user.get(0).getUserName());
            return user;
//        request.setAttribute("username", user.get(0).getUserName());
    }

    @ResponseBody
    @GetMapping(value = "/login")
    public Map<String, Object> login(@RequestParam("loginName") String loginName,@RequestParam("loginPassword") String loginPassword) {
        Map<String,Object> map = new HashMap<>();
        SysUser user = new SysUser(loginName,loginPassword);
        if(sysUserService.login(user)){
            String token= TokenUtil.sign(user);
            if (token!=null){
                map.put("code","10000");
                map.put("message","登录成功");
                map.put("token",token);
                return map;
            }
        }
        map.put("code","50000");
        map.put("message","登录失败");
        return map;
    }

}